package main.java.sokoban;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;

public class LevelSelectPanel extends JPanel {
    private final JFrame topFrame;

    public LevelSelectPanel(JFrame frame){
        this.topFrame = frame;

        setLayout(null);//使用绝对布局
        setPreferredSize(new Dimension(400, 300));
        setBackground(Color.WHITE);

        addLevelButton();
    }

    private void addLevelButton(){
        int btnSize = 64;
        int padding = 15;

        for (int i = 1; i <= 10; i++) {
            ImageIcon icon = new ImageIcon(getClass().getClassLoader().getResource("level_" + i + ".png"));
            Image scaledImage = icon.getImage().getScaledInstance(45, 45, Image.SCALE_SMOOTH);
            JButton levelButton = new JButton(new ImageIcon(scaledImage));

            levelButton.setBounds(
                    (i - 1) % 5 * (btnSize + padding) + 20,
                    (i - 1) / 5 * (btnSize + padding) + 20,
                    btnSize,
                    btnSize
            );

            levelButton.setBorderPainted(false);
            levelButton.setContentAreaFilled(false);
            levelButton.setFocusPainted(false);

            final int level = i;
            levelButton.addActionListener(e -> startLevel(level));

            add(levelButton);
        }
    }

    private void startLevel(int level) {
        char[][] map = LevelManager.getLevel(level);
        if(map != null){
            GamePanel gamePanel = new GamePanel(map, level);
            topFrame.setContentPane(gamePanel);
            topFrame.pack();
            topFrame.setLocationRelativeTo(null);
            topFrame.validate();

            gamePanel.requestFocusInWindow();
        }else{
            JOptionPane.showMessageDialog(this, "没有更多关卡了！");
        }
    }
}
